package cn.toma.service.impl.sys;

import cn.toma.common.vo.StringPool;
import cn.toma.core.AbstractService;
import cn.toma.dao.sys.UserMapper;
import cn.toma.dao.sys.UserRoleMapper;
import cn.toma.dto.UserRoleDeptDto;
import cn.toma.manager.sys.UserManager;
import cn.toma.model.sys.User;
import cn.toma.model.sys.UserRole;
import cn.toma.service.sys.UserRoleService;
import cn.toma.service.sys.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends AbstractService<User> implements UserService
{

	@Resource
	private UserRoleMapper userRoleMapper;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private UserManager userManager;

	@Resource
	private UserMapper userMapper;


	@Override
	public User findByName(String username)
	{
		return this.userMapper.findDetail(username);
	}


	@Override
	public List<User> findUserDetail(User user)
	{
		try {
			return this.userMapper.findUserDetail(user);
		} catch (Exception e) {
			log.error("查询用户异常", e);
			return null;
		}
	}

	@Override
	@Transactional
	public void updateLoginTime(String username) throws Exception
	{
		User user = new User();
		user.setLastLoginTime(new Date());


		Weekend<User> weekend = new Weekend<>(User.class);
		WeekendCriteria<User, Object> weekendCriteria = weekend.weekendCriteria();
		weekendCriteria.andEqualTo(User::getUsername, username);
		this.userMapper.updateByConditionSelective(user, weekend);

	}

	@Override
	@Transactional
	public void createUser(User user) throws Exception
	{
		// 创建用户
		user.setCreateTime(new Date());
		user.setAvatar(User.DEFAULT_AVATAR);
		save(user);

		// 保存用户角色
		String[] roles = user.getRoleId().split(StringPool.COMMA);
		setUserRoles(user, roles);


	}

	@Override
	@Transactional
	public void updateUser(User user) throws Exception
	{
		// 更新用户
		user.setPassword(null);
		user.setModifyTime(new Date());
		this.userMapper.updateByPrimaryKeySelective(user);


		Weekend<UserRole> weekend = new Weekend<>(UserRole.class);
		WeekendCriteria<UserRole, Object> weekendCriteria = weekend.weekendCriteria();
		weekendCriteria.andEqualTo(UserRole::getUserId, user.getUserId());
		this.userRoleMapper.deleteByCondition(weekend);

		String[] roles = user.getRoleId().split(StringPool.COMMA);
		setUserRoles(user, roles);

	}

	@Override
	@Transactional
	public void deleteUsers(String[] userIds) throws Exception
	{


		List<String> list = Arrays.asList(userIds);

		list.forEach(item ->
		{
			this.userMapper.deleteByPrimaryKey(item);
		});


		// 删除用户角色
		this.userRoleService.deleteUserRolesByUserId(userIds);
	}

	@Override
	@Transactional
	public void updateProfile(User user) throws Exception
	{
		this.userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	@Transactional
	public void updateAvatar(String username, String avatar) throws Exception
	{
		User user = new User();
		user.setAvatar(avatar);

		Weekend<User> weekend = new Weekend<>(User.class);
		weekend.weekendCriteria().andEqualTo(User::getUsername, username);
		this.userMapper.updateByConditionSelective(user, weekend);

	}

	@Override
	@Transactional
	public void updatePassword(String username, String password) throws Exception
	{
		User user = new User();
		user.setPassword(password);

		Weekend<User> weekend = new Weekend<>(User.class);
		weekend.weekendCriteria().andEqualTo(User::getUsername, username);
		this.userMapper.updateByConditionSelective(user, weekend);


	}

	@Override
	@Transactional
	public void regist(String username, String password) throws Exception
	{
		User user = new User();
		user.setPassword(password);
		user.setUsername(username);
		user.setCreateTime(new Date());
		user.setStatus(User.STATUS_VALID);
		user.setSsex(User.SEX_UNKNOW);
		user.setAvatar(User.DEFAULT_AVATAR);
		user.setDescription("注册用户");
		this.save(user);

		UserRole ur = new UserRole();
		ur.setUserId(user.getUserId());
		ur.setRoleId(2L); // 注册用户角色 ID
		this.userRoleMapper.insert(ur);

	}

	@Override
	@Transactional
	public void resetPassword(String[] usernames, String encrypt) throws Exception
	{
		for (String username : usernames) {

			User user = new User();
			user.setPassword(encrypt);

			Weekend<User> weekend = new Weekend<>(User.class);
			weekend.weekendCriteria().andEqualTo(User::getUsername, username);
			this.userMapper.updateByConditionSelective(user, weekend);


		}

	}

	/**
	 * 根据角色名称 部门ID 获取人员
	 *
	 * @param userRoleDeptDto
	 * @return
	 */
	@Override
	public UserRoleDeptDto findUserRoleDept(UserRoleDeptDto userRoleDeptDto)
	{
		return this.userMapper.findUserRoleDept(userRoleDeptDto);
	}

	private void setUserRoles(User user, String[] roles)
	{
		Arrays.stream(roles).forEach(roleId ->
		{
			UserRole ur = new UserRole();
			ur.setUserId(user.getUserId());
			ur.setRoleId(Long.valueOf(roleId));
			this.userRoleMapper.insert(ur);
		});
	}
}
